//==========================================================================
// Copyright (c) 2000-2008,  Elastos, Inc.  All Rights Reserved.
//==========================================================================
#define __NO_LINKNODE_CONSTRUCTOR
#include <mantle.h>

static DLinkNode s_eventList = { &s_eventList, &s_eventList };

#ifdef DEBUG_KMUTEX
static KMutex s_listLock(__FILE__, __LINE__);
#else 
static KMutex s_listLock;
#endif //DEBUG_KMUTEX

CSystemEvent *CreateSystemEvent(CProcess *pOwner, Boolean bManualReset)
{
    CSystemEvent *pSysEvent;

    pSysEvent = new CSystemEvent(pOwner, bManualReset);
    if (NULL == pSysEvent) return NULL;

    s_listLock.Lock();
    s_eventList.InsertPrev(pSysEvent);
    s_listLock.Unlock();

    pSysEvent->AddRef();
    return pSysEvent;
}

void DetachSystemEvent(CSystemEvent *pSystemEvent)
{
    s_listLock.Lock();
    pSystemEvent->Detach();
    s_listLock.Unlock();
}

void TriggerSystemEvent(SystemEvent sysEvent)
{
    assert(0 != sysEvent);
    CSystemEvent *pSystemEvent;

    s_listLock.Lock();
    ForEachDLinkNode(CSystemEvent *, pSystemEvent, &s_eventList) {
        pSystemEvent->Trigger(sysEvent);
    }
    s_listLock.Unlock();
}

void ClearSystemEvent(SystemEvent sysEvent)
{
    assert(0 != sysEvent);
    CSystemEvent *pSystemEvent;

    s_listLock.Lock();
    ForEachDLinkNode(CSystemEvent *, pSystemEvent, &s_eventList) {
        pSystemEvent->Clear(sysEvent);
    }
    s_listLock.Unlock();
}

void TriggerSystemEvent(CProcess *pOwner, SystemEvent sysEvent)
{
    assert(0 != sysEvent);
    CSystemEvent *pSystemEvent;

    s_listLock.Lock();
    ForEachDLinkNode(CSystemEvent *, pSystemEvent, &s_eventList) {
        if (pOwner == pSystemEvent->m_pOwner) {
            pSystemEvent->Trigger(sysEvent);
            break;
        }
    }
    s_listLock.Unlock();
}

void ClearSystemEvent(CProcess *pOwner, SystemEvent sysEvent)
{
    assert(0 != sysEvent);
    CSystemEvent *pSystemEvent;

    s_listLock.Lock();
    ForEachDLinkNode(CSystemEvent *, pSystemEvent, &s_eventList) {
        if (pOwner == pSystemEvent->m_pOwner) {
            pSystemEvent->Clear(sysEvent);
            break;
        }
    }
    s_listLock.Unlock();
}
